#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import pycurl
import StringIO
import sys
import json

def getPMC(ids):
    url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
    buf = StringIO.StringIO()
    c = pycurl.Curl()
    c.setopt(pycurl.POST, 1)
    c.setopt(c.URL, url)
    c.setopt(pycurl.HTTPPOST, [('db', 'pubmed'), ('id', ids), ('retmode', 'xml')])
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.perform()
    outfile = open("pubmed_meta.xml", "w")
    outfile.write(buf.getvalue())
    outfile.close()
    buf.close()

if __name__ == '__main__':
    f=file(sys.argv[1])
    s=json.load(f)
    f.close()

    ids=""
    for id in s["esearchresult"]["idlist"]:
        ids+=str(id)+","
    ids=ids[:-1]
    print ids

    getPMC(ids)